package com.hnxxxy.rewardmgr.service.impl;

import com.hnxxxy.common.AjaxRtnEntity.AjaxRtnEntity;
import com.hnxxxy.rewardmgr.bean.ExcelBean;
import com.hnxxxy.rewardmgr.bean.NumberConfig;
import com.hnxxxy.rewardmgr.bean.RewardLevel;
//import com.hnxxxy.rewardmgr.utils.MessageUtils;
import com.hnxxxy.rewardmgr.utils.Variable;
import org.springframework.beans.factory.annotation.Autowired;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import com.hnxxxy.rewardmgr.mapper.RewardMapper;
import com.hnxxxy.rewardmgr.service.RewardService;
import sun.misc.MessageUtils;

import java.security.SecureRandom;
import java.util.*;

@Service
@Slf4j
public class RewardServiceImpl implements RewardService {
    @Autowired(required = false)
    private RewardMapper rewardMapper;

    @Override
    public List<RewardLevel> loadRewardLevel() {
        return rewardMapper.loadRewardLevel();
    }

    @Override
    public List<NumberConfig> loadNumberConfig(String name, String numbers, String rwd_state) {
        System.out.println(name + "   " + numbers);
        return rewardMapper.loadNumberConfig(name, numbers, rwd_state);
    }

    @Override
    public int deleteRewardLevel(int id) {
        try {
            rewardMapper.deleteRewardLevel(id);
            return AjaxRtnEntity.success;
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxRtnEntity.error;
        }
    }

    @Override
    public int updateRewardLevel(RewardLevel rwd) {
        try {
            rewardMapper.updateRewardLevel(rwd);
            return AjaxRtnEntity.success;
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxRtnEntity.error;
        }
    }

    @Override
    public void truncateRatioConfig() {
        rewardMapper.truncateRatioConfig();
    }

    @Override
    public int insertRewardLevel(RewardLevel rwd) {
        return rewardMapper.insertRewardLevel(rwd);

    }

    @Override
    public int insertRewardNotFond(RewardLevel rwd) {
        return rewardMapper.insertRewardNotFond(rwd);
    }

    @Override
    public List<NumberConfig> numberConfig() {
        return rewardMapper.numberConfig();
    }

    @Override
    public List<NumberConfig> numberConfig(int role) {
        return rewardMapper.numberConfigByRole(role);
    }

    @Override
    public List<NumberConfig> numberRatioConfig(int rwd_state) {
        return rewardMapper.numberRatioConfig(rwd_state);
    }

    @Override
    public RewardLevel levelConfigById(int id) {
        return rewardMapper.levelConfigById(id);
    }


    @Override
    public int deleteNumberConfig(String id) {
        return rewardMapper.deleteNumberConfig(id);
    }

    @Override
    public int updateNumberConfig(NumberConfig numberConfig) {
        return rewardMapper.updateNumberConfig(numberConfig);
    }

    @Override
    public int insertNumberConfig(NumberConfig numberConfig) {
        return rewardMapper.insertNumberConfig(numberConfig);
    }

    @Override
    public int insertRatio(List<NumberConfig> numberConfig) {
        return rewardMapper.insertRatio(numberConfig);
    }

    @Override
    public List<NumberConfig> showReward() {
        return rewardMapper.showReward();
    }

    @Override
    public int deleteRwdRatioConfig(int id) {
        return rewardMapper.deleteRwdRationConfig(id);
    }

    @Override
    public int batchInsertNumberConfig(List<ExcelBean> list) {
        return rewardMapper.batchInsertNumberConfig(list);
    }

    @Override
    public int sysSMSConfig() {
        return rewardMapper.sysSMSConfig();
    }


    @Override
    public Map<String, Object> getAll() {
        //初始化清空临时缓存
        Variable.Stu_temp.clear();
        Variable.Teacher_temp.clear();
        Variable.All_temp.clear();

        //从初始化缓存获得临时数据
        Variable.Stu_temp.addAll(Variable.numberConfigListAllOfStu);
        Variable.Teacher_temp.addAll(Variable.numberConfigListAllOfTeacher);
        Variable.All_temp.addAll(Variable.numberConfigListAll);
        //是否发送短信
        Variable.isSMS = rewardMapper.sysSMSConfig();

        //先截断获奖人表
        rewardMapper.truncateRatioConfig();

        Map<String, Object> map = new HashMap<>();

        //总人数，这里总人数不变
        Variable.size = Variable.All_temp.size();

        //得到所有奖项列表
        List<RewardLevel> rewardLevels = rewardMapper.loadRewardLevel();

        //装入奖励数据返回前台
        map.put("option", rewardLevels);

        //返回所有人
        map.put("data", Variable.All_temp);
        return map;
    }

    @Override
    public Map<String, List<NumberConfig>> getRatioNumber(int id) {
        //根据奖项id查出抽奖的数据
        RewardLevel rewardLevel = rewardMapper.levelConfigById(id);
        //如果没有当前奖项数据，则复制id为1的奖项数据到此项
        if (rewardLevel == null) {
            RewardLevel rewardLevel1 = rewardMapper.levelConfigById(1);
            rewardLevel1.setName(rewardLevel1.getName().replaceAll("1", String.valueOf(id)));
            rewardLevel1.setId(id);
            rewardMapper.insertRewardNotFond(rewardLevel1);
            rewardLevel = rewardLevel1;
        }

        //先合并
        //numberConfigListAll.addAll(rewardServiceImpl.numberRatioConfig(id));

        /*现在不需要干这一步
        //先删除数据库中与当前抽奖相同的记录
        rewardServiceImpl.deleteRwdRatioConfig(id);
        */
        Map<String, List<NumberConfig>> map = new HashMap<>();

        //临时list获取抽中奖的人
        List<NumberConfig> list;

        List<NumberConfig> configList;

        //抽奖人数
        int num;

        //获取奖励表状态
        int isRation = rewardLevel.getIs_ratio();
        //判断当前奖励是人数还是比例，0为比例，1为人数
        if (isRation != 1) {
            num = (int) rewardLevel.getRatio();
        } else {
            num = (int) (Variable.size * rewardLevel.getRatio());
            num = num == 0 ? 1 : num;
        }

        //判断抽奖人的类型，学生还是老师？
        if (rewardLevel.getRole() == null) {
            configList = Variable.All_temp;
        } else {
            if (rewardLevel.getRole() == 0) {
                configList = Variable.Stu_temp;
            } else if (rewardLevel.getRole() == 1) {
                configList = Variable.Teacher_temp;
            } else {
                configList = Variable.All_temp;
            }
        }
        /*configList = (rewardLevel.getRole() == 0)?
                Variable.numberConfigListAllOf0:
                Variable.numberConfigListAllOf1;*/
        //0为学生抽奖，1为老师抽奖，抽中奖的人数
        list = reList(configList, num, id, rewardLevel.getName());
        map.put(rewardLevel.getName(), list);

        //将中奖人数插入数据库
        rewardMapper.insertRatio(list);
        return map;
    }

    @Override
    public int cleanNumberConfig() {
        return this.rewardMapper.cleanNumberConfig();
    }

    @Override
    public int batchDeleteLevel(List<Integer> list) {
        return this.rewardMapper.batchDeleteLevel(list);
    }

    /**
     * @param list      需要抽奖的人
     * @param size      需要抽到人数
     * @param id        抽奖后的状态
     * @param leve_name 奖励等级名称
     * @return
     */
    public List<NumberConfig> reList(List<NumberConfig> list, int size, int id, String leve_name) {
        //先判断list容量
        if (size > list.size()) {
            return null;
        }
        //定义真随机数，不能使用SecureRandom.getInstanceStrong();定义，否则可能会阻塞线程
        SecureRandom secureRandom = new SecureRandom();

        //临时customers存储中奖人数并返回
        List<NumberConfig> customers = new ArrayList<>();
        if (Variable.isSMS != 0) {
            //循环取size个中奖人数
            for (int i = 0; i < size; i++) {

                //从传入的list删除随机下标的元素，并把该元素存进临时customers里面
                customers.add(list.remove(secureRandom.nextInt(list.size())));

                //修改当前中奖人的中奖状态
                customers.get(i).setRwd_state(id);
                customers.get(i).setLevel_name(leve_name);

                //发送短信
//                MessageUtils.toStartSendMessage(customers.get(i));
            }
        } else {
            //循环取size个中奖人数
            for (int i = 0; i < size; i++) {

                NumberConfig remove = list.remove(secureRandom.nextInt(list.size()));
                //从传入的list删除随机下标的元素，并把该元素存进临时customers里面
                customers.add(remove);

                //修改当前中奖人的中奖状态
                customers.get(i).setRwd_state(id);
                customers.get(i).setLevel_name(leve_name);

                //同步删除其他两个缓存
                this.removeRewardObject(remove, list);
            }
        }
        return customers;
    }

    /**
     * 缓存同步
     *
     * @param numberConfig
     * @param list
     */
    private void removeRewardObject(NumberConfig numberConfig, List<NumberConfig> list) {
        if (list == Variable.All_temp) {
            Variable.Stu_temp.remove(numberConfig);
            Variable.Teacher_temp.remove(numberConfig);
        } else if (list == Variable.Stu_temp) {
            Variable.All_temp.remove(numberConfig);
            Variable.Teacher_temp.remove(numberConfig);
        } else if (list == Variable.Teacher_temp) {
            Variable.All_temp.remove(numberConfig);
            Variable.Stu_temp.remove(numberConfig);
        }
    }
}